package com.lzx.iteam;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.*;
import com.lzx.iteam.adapter.AttendanceCountMonthAdapter;
import com.lzx.iteam.adapter.AttendanceTeamAdapter;
import com.lzx.iteam.adapter.CRMMainAdapter;
import com.lzx.iteam.adapter.SalaryGroupAdapter;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.AttendanceData;
import com.lzx.iteam.bean.DateData;
import com.lzx.iteam.bean.SalaryGroupBean;
import com.lzx.iteam.bean.SalaryRuleBean;
import com.lzx.iteam.net.*;
import com.lzx.iteam.util.Constants;
import com.lzx.iteam.util.PreferenceUtil;
import com.lzx.iteam.util.StringUtil;
import com.lzx.iteam.widget.DividerGridView;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2017年 01月 09日
 * Time: 下午2:31
 *
 * @QQ : 1234567890
 * **********************************
 *
 * 工资主页面
 */
public class SalaryMainActivity extends MyBaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {

    @FindViewById(id = R.id.ll_salary_main_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.tv_salary_main_team)
    private TextView mTvTeams;
    @FindViewById(id = R.id.tv_salary_main_form)
    private TextView mTvForm;
    @FindViewById(id = R.id.ll_salary_main_title)
    private LinearLayout mLayouTeams;
    @FindViewById(id = R.id.iv_salary_arrow)
    private ImageView mIvArrow;
    @FindViewById(id = R.id.ll_salary_date_select)
    private LinearLayout mLayoutDate;
    @FindViewById(id = R.id.tv_salary_date)
    private TextView mTvDate;
    @FindViewById(id = R.id.iv_salary_date_arrow)
    private ImageView mIvDateArrow;
    @FindViewById(id = R.id.gv_salary_main)
    private DividerGridView mGridView;
    @FindViewById(id = R.id.tv_salary_calculate)
    private TextView mTvCalculate;

    private CRMMainAdapter mAdapter;
    private Dialog mTeamDialog;
    private String mTextArray[] = {"考勤规定", "五险一金", "个人税务"};
    private int mImageArray[] = {R.drawable.iv_salary_attendance, R.drawable.iv_salary_five, R.drawable.iv_salary_tax};
    private ArrayList<SalaryGroupBean> mGroups;
    private SalaryGroupBean mGroup;
    private SalaryRuleBean mRuleData;
    private PopupWindow mDatePop;
    private ArrayList<DateData> mDateDatas = new ArrayList<DateData>();

    private String mGroupId;
    private DateData mSelectDate;
    private final int GET_SALARY_GROUPS = 1000;
    private final int ACTIVITY_REQUEST = 10001;
    private final int GET_SALARY_RULE = 30001;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            waitDlgDismiss();
            if (msg.arg1 == 0) {
                switch (msg.what) {
                    case GET_SALARY_GROUPS:
                        mGroups = (ArrayList<SalaryGroupBean>) msg.obj;
                        if (mGroups != null && mGroups.size() > 0) {
                            mIvArrow.setVisibility(View.VISIBLE);
                            mGroupId = PreferenceUtil.getInstance(mActivity).getString(PreferenceUtil.SALARY_GROUP_ID, "");
                            if (!StringUtil.isEmpty(mGroupId)) {
                                for (int i = 0; i < mGroups.size(); i++) {
                                    SalaryGroupBean bean = mGroups.get(i);
                                    if (mGroupId.equals(bean.getGroup_id())) {
                                        mGroup = bean;
                                        mGroupId = mGroup.getGroup_id();
                                        break;
                                    }
                                }
                            }
                            if (StringUtil.isEmpty(mGroupId) || mGroup == null) {
                                mGroup = mGroups.get(0);
                                mGroupId = mGroup.getGroup_id();
                            }
                            mTvTeams.setText(mGroup.getGroup_name());
                            mRuleData = mGroup.getGroup_rule();
                        } else {
                            mIvArrow.setVisibility(View.GONE);
                        }
                        break;
                    case GET_SALARY_RULE:
                        if (msg.obj == null) {
                            Log.d("My_Rule"," rule = null");
                        }else{
                            mRuleData = (SalaryRuleBean) msg.obj;
                        }
                        break;
                }

            } else {
                Toast.makeText(mActivity, (String) msg.obj,
                      Toast.LENGTH_LONG).show();
            }

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.salary_main_layout);
    }

    @Override
    public void initListener() {
        mLayoutBack.setOnClickListener(this);
        mLayouTeams.setOnClickListener(this);
        mTvForm.setOnClickListener(this);
        mTvCalculate.setOnClickListener(this);
        mGridView.setOnItemClickListener(this);
        mLayoutDate.setOnClickListener(this);
    }

    @Override
    public void initData() {

        mAdapter = new CRMMainAdapter(mActivity, mTextArray, mImageArray);
        mGridView.setAdapter(mAdapter);

        Calendar c = Calendar.getInstance();
        int temp_year = c.get(Calendar.YEAR);
        int temp_month = c.get(Calendar.MONTH) + 1; //通过Calendar算出的月数要+1

        for (int i = 0; i < 3; i++) {
            DateData dateData1 = new DateData();
            if (temp_month == 1) {
                temp_month = 12;
                temp_year = temp_year - 1;
                dateData1.setMonth(temp_month);
                dateData1.setYear(temp_year);
            } else {
                temp_month = temp_month - 1;
                dateData1.setMonth(temp_month);
                dateData1.setYear(temp_year);
            }
            mDateDatas.add(dateData1);
        }
        mSelectDate = mDateDatas.get(0);
        mTvDate.setText("选择时间：" + String.format("%s年%s月", mSelectDate.getYear(), mSelectDate.getMonth()));

        waitDlgShow();
        getGroups();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACTIVITY_REQUEST) {
            getSalaryRule();
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_salary_main_back:
                finish();
                break;
            case R.id.tv_salary_main_form:
                if (!StringUtil.isEmpty(mGroupId)) {
                    Intent form = new Intent(mActivity, SalaryListActivity.class);
                    form.putExtra("group_id", mGroupId);
                    form.putExtra("salary_rule", mRuleData);
                    startActivity(form);
                } else {
                    showShortToast("薪酬计算器仅提供给企业老板使用");
                }
                break;
            case R.id.tv_salary_calculate:
                if (!StringUtil.isEmpty(mGroupId)) {
                    Intent calculate = new Intent(mActivity, SalaryFieldFormActivity.class);
                    calculate.putExtra("group_id", mGroupId);
                    calculate.putExtra("salary_rule", mRuleData);
                    calculate.putExtra("month", mSelectDate);
                    startActivity(calculate);
                } else {
                    showShortToast("薪酬计算器仅提供给企业老板使用");
                }
                break;
            case R.id.ll_salary_main_title:
                if (mGroups != null && mGroups.size() > 0) {
                    if (mIvArrow.getDrawable().getCurrent().getConstantState()
                          .equals(getResources().getDrawable(R.drawable.arrow_up).getConstantState())) {
                        mIvArrow.setImageResource(R.drawable.arrow_down);
                    } else {
                        mIvArrow.setImageResource(R.drawable.arrow_up);
                        showTeamDialog();
                    }
                } else {
                    showShortToast("薪酬计算器仅提供给企业老板使用");
                }
                break;
            case R.id.ll_salary_date_select:
                if (mDatePop != null && mDatePop.isShowing()) {
                    mIvDateArrow.setImageResource(R.drawable.iv_turn_up);
                } else {
                    mIvDateArrow.setImageResource(R.drawable.iv_turn_down);
                    showMonthPopwindow();
                }
                break;

        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (StringUtil.isEmpty(mGroupId)) {
            showShortToast("薪酬计算器仅提供给企业老板使用");
            return;
        }
        switch (position) {
            case 0:
                Intent rule = new Intent(mActivity, SalaryRuleActivity.class);
                rule.putExtra("group_id", mGroupId);
                rule.putExtra("salary_rule", mRuleData);
                startActivityForResult(rule, ACTIVITY_REQUEST);
                break;
            case 1:
                Intent wxyj = new Intent(mActivity, SalaryWXYJFromActivity.class);
                wxyj.putExtra("group_id", mGroupId);
                wxyj.putExtra("salary_rule", mRuleData);
                startActivityForResult(wxyj, ACTIVITY_REQUEST);
                break;
            case 2:
                Intent tax = new Intent(mActivity, SalaryTaxActivity.class);
                tax.putExtra("group_id", mGroupId);
                tax.putExtra("salary_tax", mRuleData.getSalary_tax());
                startActivityForResult(tax, ACTIVITY_REQUEST);
                break;
        }
    }

    /**
     * 弹出中间团队选择
     */
    private void showTeamDialog() {

        mTeamDialog = new AlertDialog.Builder(this)
              .create();
        mTeamDialog.show();
        Window window = mTeamDialog.getWindow();
        WindowManager.LayoutParams lp = mTeamDialog.getWindow().getAttributes();
        lp.dimAmount = 0.3f; // TODO 设置黑暗度  0.0f完全不暗，1.0f全暗
//        lp.alpha = 0.5f;   // TODO 设置透明度    0.0f完全透明，1.0完全不透明
        window.setAttributes(lp);
        // 设置布局
        window.setContentView(R.layout.attendance_team_pop_layout);
        // 设置宽高
        window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        // 设置弹出的动画效果
        window.setWindowAnimations(R.style.Ap_Pop_Style);

        ListView listView = (ListView) window.findViewById(R.id.lv_attendance_team_list);
        LinearLayout cancelLayout = (LinearLayout) window.findViewById(R.id.dialog_cancel);


        SalaryGroupAdapter adapter = new SalaryGroupAdapter(mActivity, mGroups);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mGroup = mGroups.get(i);
                mGroupId = mGroup.getGroup_id();
                PreferenceUtil.getInstance(mActivity).save(PreferenceUtil.SALARY_GROUP_ID, mGroupId);
                mTvTeams.setText(mGroup.getGroup_name());
                mRuleData = mGroup.getGroup_rule();

                mTeamDialog.dismiss();
            }
        });

        cancelLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTeamDialog.dismiss();
            }
        });
        mTeamDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                mIvArrow.setImageResource(R.drawable.arrow_down);
            }
        });

    }

    /**
     * 弹出日期选择
     */
    private void showMonthPopwindow() {

        View popView = LayoutInflater.from(mActivity).inflate(R.layout.dialog_list_layout, null);
        int popWidth = Constants.dip2px(this, 160);
        if (mDatePop == null) {
            mDatePop = new PopupWindow(popView,
                  popWidth,
                  WindowManager.LayoutParams.WRAP_CONTENT);
            mDatePop.setFocusable(true);
            mDatePop.setOutsideTouchable(true);
            mDatePop.setBackgroundDrawable(new ColorDrawable(
                  Color.TRANSPARENT));
        }
        int xOffSet = (getWindowManager().getDefaultDisplay().getWidth() - popWidth) / 2;
        int yOffSet = Constants.dip2px(this, 174);

        mDatePop.showAsDropDown(mLayoutDate, xOffSet, -yOffSet);
//        mDatePop.setAnimationStyle(R.style.Ap_Pop_Style);

        ListView listView = (ListView) popView.findViewById(R.id.lv_dialog);

        AttendanceCountMonthAdapter adapter = new AttendanceCountMonthAdapter(mActivity);
        adapter.bindData(mDateDatas);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                mSelectDate = mDateDatas.get(i);
                mTvDate.setText("选择时间：" + String.format("%s年%s月", mSelectDate.getYear(), mSelectDate.getMonth()));
                mDatePop.dismiss();
            }
        });

        mDatePop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mIvDateArrow.setImageResource(R.drawable.iv_turn_up);
            }
        });

    }

    /**
     * 获取考勤团队
     */
    private void getGroups() {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        GetSalaryGroupsMsg msg = new GetSalaryGroupsMsg(mHandler.obtainMessage(GET_SALARY_GROUPS));
        msg.mApi = AsynHttpClient.API_SALARY_MY_GROUPS;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(msg);

    }

    /**
     * 获取规则
     */
    private void getSalaryRule() {
        waitDlgShow();
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin
              .getInstance().mSid));
        nvps.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        GetSalaryRuleMsg msg = new GetSalaryRuleMsg(mHandler.obtainMessage(GET_SALARY_RULE));
        msg.mApi = AsynHttpClient.API_SALARY_GET_RULE;
        msg.mParams = nvps;
        AsynHttpClient.getInstance(this).execEventHttp(msg);

    }
}
